package Day14;


import java.util.ArrayList;
import java.util.Random;

public class DoExpress {
    private ArrayList<Express> list = new ArrayList<>(100);
    private Random r = new Random();
    private int size = 0;

    //添加快递
    public boolean add(Express e) {
        if (list.size() == 100) {
            return false;
        }
        Express m = findByNumber(e.getNumber());
        if(m == null){
            int code = randomCope();
            int gui = randomGui();
            e.setCode(code);
            e.setGui(gui);
            System.out.print("取件码为 " + e.getCode() + "\t");
            System.out.println("快递柜为 " + e.getGui());
            list.add(e);
            return true;
        }else {
            return false;
        }
    }

    //随机生成柜子
    public int randomGui(){
        while (true) {
            int a = r.nextInt(90) + 10;
            for (int i = 0; i < list.size(); i++) {
                if(a != list.get(i).getGui()){
                }else{
                    a = r.nextInt(90) +10;
                }
            }
            return a;
        }
    }

    //随机生成取件码
    public int randomCope(){
        while(true){
            int code = r.nextInt(90000) + 10000;
            Express e = getExpress(code);
            if(e == null){
                return code;
            }
        }
    }

    //取件码取件
    public Express getExpress(int code){
        for (int i = 0; i < list.size(); i++) {
            if(list.size() != 0 && list.get(i).getCode() == code){
                return list.get(i);
            }
        }
        return null;
    }

    //寻找快递单号
    public Express findByNumber(int number){
        for (int i = 0; i < list.size(); i++) {
            if(number == list.get(i).getNumber()){
                return list.get(i);
            }
        }
        return null;
    }

    //删除快递
    public void delete(Express e){
        int i = -1;
        aa:for (i = 0; i < list.size(); i++) {
            if(e.getNumber() == list.get(i).getNumber()){
                list.remove(i);
                break aa;
            }
        }
        if(i == -1){
            System.out.println("找不到该快递");
        }
    }

    //修改快递
    public void revise(Express oldE,Express newE) {
        delete(oldE);
        add(newE);
    }

    public void printlnAll(){
        System.out.println("快递单号(number)\t\t快递公司(company)\t\t取件码(code)\t\t柜子(gui)");
        if(list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).toString());
            }
        }else{
            System.out.println("暂无快递信息");
        }
    }

    public void user(){
        View v = new View();
        int code = v.user();
        Express a = getExpress(code);
        if(a == null){
            System.out.println("取件失败");
        }else{
            System.out.println("快递信息为" + a);
            System.out.println("取件成功");
            delete(a);
        }

    }
}
